package com.myself.ssoserver.config

import com.auth0.jwt.JWT
import com.fasterxml.jackson.databind.ObjectMapper
import com.myself.ssoserver.dto.AuthException
import com.myself.ssoserver.entity.User
import com.myself.ssoserver.service.SessionService
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter
import javax.naming.AuthenticationException

@Component
class JwtAuthFilter(
    private val sessionService: SessionService
) : OncePerRequestFilter() {

    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        chain: FilterChain
    ) {
        val token = extractToken(request)
        if (token != null && sessionService.validateToken(token)) {
            val claims = JWT.decode(token)
            val userJson = claims.getClaim("user").asString()
            val objectMapper = ObjectMapper()
            val user = objectMapper.readValue(userJson, User::class.java)
            val authentication = UsernamePasswordAuthenticationToken(
                user,
                null,
                emptyList()
            )
            SecurityContextHolder.getContext().authentication = authentication
        }
        chain.doFilter(request, response)
    }

    private fun extractToken(request: HttpServletRequest): String? {
        return request.getHeader("Authorization")?.substringAfter("Bearer ")
    }
}